<template>
  <scroll
    class="suggest"
    ref="suggest"
    :data="result"
    :pullup="pullup"
    @scrollToEnd="searchMore"
    :beforeScroll="beforeScroll"
    @beforeScroll="listScroll"
  >
    <ul class="suggest-list">
      <li class="suggest-item" v-for="(item, index) in result" :key="index" @click="selectItem(item)">
        <div class="icon">
          <i :class="getIconCls(item)"></i>
        </div>
        <div class="name">
          <p class="text" v-html="getDisplayName(item)"></p>
        </div>
      </li>
      <loading v-show="hasMore" title=""></loading>
    </ul>
    <div class="no-result-wrapper" v-show="!hasMore && !result.length">
      <no-result title="抱歉，暂无搜索结果"></no-result>
    </div>
  </scroll>
</template>

<script>
  import {search} from "api/search";
  import {ERR_OK} from "api/config";
  import {createSong} from 'common/js/song';
  import Scroll from 'base/scroll/scroll';
  import Loading from 'base/loading/loading';
  import Singer from 'common/js/singer';
  import {mapMutations,mapActions} from 'vuex';
  import NoResult from 'base/no-result/no-result';
  import {getMusic} from "api/singer";

  const TYPE_SINGER = 'singer';

  const perpage = 20; // 请求的条数
  export default {
    name: "suggest",
    data() {
      return {
        page: 1,
        result: [],
        pullup: true, // 开启上拉刷新
        hasMore: true, // 用作加载更多的标识
        beforeScroll: true // 滚动的时候让键盘弹起
      }
    },
    props: {
      query: {
        type: String,
        default: ''
      },
      showSinger: {
        type: Boolean,
        default: true
      }
    },
    methods: {
      ...mapMutations({
        setSinger: 'SET_SINGER'
      }),
      ...mapActions([
        'insertSong'
      ]),
      search () {
        // keyword改变时重置scroll到顶部
        this.page = 1;
        this.hasMore = true;
        this.$refs.suggest.scrollTo(0,0);
        search(this.query, this.page,this.showSinger,perpage).then((res) => {
          if (res.code === ERR_OK) {
            this.result = this._genResult(res.data);
            // this.result = this._normalizeSongs(res.data.song.list);
            this._checkMore(res.data);
          }
        })
      },
      // 上拉加载更多
      searchMore () {
        if (!this.hasMore) {
          return
        }
        this.page++;
        search(this.query,this.page,this.showSinger,perpage).then((res) => {
          if (res.code === ERR_OK) {
            console.log("res",res);
            this.result = this.result.concat(this._genResult(res.data));
            // this.result = this.result.concat(this._normalizeSongs(res.data.song.list));


            this._checkMore(res.data)

          }
        })
      },
      getIconCls (item) {
        if (item.type === TYPE_SINGER) {
          return 'icon-mine'
        } else {
          return 'icon-music'
        }
      },
      getDisplayName (item) {
        console.log('getDisplayName item',item);
        if (item.type === TYPE_SINGER) {
          return item.singername
        } else {
          return `${item.name}---${item.singer}`
        }
      },
      // 点击搜索列表的时候
      selectItem (item) {
        console.log('selectItem item',item);
        // 如果type时一个歌手要跳转到歌手的详情页
        if (item.type === TYPE_SINGER) {
          const singer = new Singer({
            id: item.singermid,
            name: item.singername,
          });
          this.$router.push({
            path: `/search/${singer.id}`
          });
          this.setSinger(singer)
        } else {
          this.insertSong(item)
        }
        // 派发一个时间，播放了。就记录下历史记录
        this.$emit('select')
      },
      _genResult(data) {
        let ret = [];
        if (data.zhida && data.zhida.singerid) {
          ret.push({...data.zhida,...{type: TYPE_SINGER}})
        }
        if (data.song) {
          console.log("data.song",data.song);
          ret = ret.concat(this._normalizeSongs(data.song.list))
        }
        console.log('_genResult ret', ret);
        return ret
      },
      _normalizeSongs (list) {
        let ret = [];
        list.forEach((musicData) => {
          if (musicData.songid && musicData.albummid) {
            ret.push(createSong(musicData))
            // getMusic(musicData.songmid).then(res=>{
            //   if (res.code === ERR_OK) {
            //     const svkey = res.data.items;
            //     const songVkey = svkey[0].vkey;
            //     const newSong = createSong(musicData,songVkey);
            //     ret.push(newSong)
            //   }
            // })
            //
          }
        });
        return ret
      },
      refresh () {
        this.$refs.suggest.refresh()
      },
      listScroll () {
          this.$emit('listScroll')
      },
      _checkMore (data) {
        const song = data.song;
        if (!song.list.length || (song.curnum + song.curpage * perpage) >= song.totalnum) {
          this.hasMore = false
        }
      },
    },
    watch: {
      // 监听输入的关键词，api请求数据
      query() {
        this.search()
      }
    },
    components: {
      Scroll,
      Loading,
      NoResult
    }
  }
</script>

<style scoped lang="stylus" rel="stylesheet/stylus">
  @import "~common/stylus/variable"
  @import "~common/stylus/mixin"

  .suggest
    height: 100%
    overflow: hidden
    .suggest-list
      padding: 0 30px
      .suggest-item
        display: flex
        align-items: center
        padding-bottom: 20px
      .icon
        flex: 0 0 30px
        width: 30px
        [class^="icon-"]
          font-size: 14px
          color: $color-text-d
      .name
        flex: 1
        font-size: $font-size-medium
        color: $color-text-d
        overflow: hidden
        .text
          no-wrap()
    .no-result-wrapper
      position: absolute
      width: 100%
      top: 50%
      transform: translateY(-50%)
</style>
